/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * 
 * Project Name:assign-tracer
 * Create Time: 2016年3月8日 下午4:21:09
 */
package com.lenovo.lmrp.server.assigntracer.spi;

import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import javax.inject.Inject;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import com.lenovo.lmrp.api.model.entity.TicketEventPO;
import com.lenovo.lmrp.base.event.EventCode;
import com.lenovo.lmrp.base.event.EventContent;
import com.lenovo.lmrp.base.event.EventSource;
import com.lenovo.lmrp.base.event.EventTopic;
import com.lenovo.sdc.framework.mq.AMQClient;
import com.lenovo.sdc.framework.util.exception.ErrorCode;
import com.lenovo.sdc.framework.util.exception.TraceableException;

/**
 * 
 * @author wujin
 * @version v1.0
 */
public class TicketAOP implements MethodInterceptor {
    private BlockingQueue<TicketEventPO> queue;
    
    @Inject
    public TicketAOP(AMQClient mqclient) {
        queue = new LinkedBlockingQueue<>();
        
        new Thread() {
            public void run() {
                while (!isInterrupted()) {
                    try {
                        TicketEventPO event = queue.take();
                        EventContent<TicketEventPO> content = new EventContent<>();
                        content.setSource(EventSource.TRACER);
                        content.setCode(EventCode.TICKET_UPDATE);
                        content.setContent(event);
                        mqclient.publish(EventTopic.TICKET_EVENT.name(), content.toJson());
                    }
                    catch (Exception exp) {
                        TraceableException.writeLog(ErrorCode.MQ_PUBLISH_FAILED, "", exp);
                    }
                }
            }
        }.start();
    }
    
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Object[] params = invocation.getArguments();
        TicketEventPO po = new TicketEventPO();
        po.setEventTime(new Date());
        po.setSource(EventSource.APP.name());
        if (invocation.getMethod().getName().equals("updateTicket")) {
            po.setItsmCode((String)params[0]);
            po.setTicketID((String) params[1]);
            po.setAction((String) params[2]);
            po.setContent(params[3]);
            queue.add(po);
        }
        Object result = invocation.proceed();
        
        return result;
    }
}
